package sz.szsmk.citizencard.ui.newversion.fragment.presenter

import com.google.gson.Gson
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.model.network.bean.response.BaseBean
import sz.szsmk.citizencard.model.network.dzbean.req.*
import sz.szsmk.citizencard.model.network.dzbean.res.*
import sz.szsmk.citizencard.mvp.dzsmkpresenter.AppBasePresenter
import sz.szsmk.citizencard.retrofitrxjava.DZSmkAppInit
import sz.szsmk.citizencard.retrofitrxjava.newversion.ApiCallback
import sz.szsmk.citizencard.retrofitrxjava.newversion.HttpDateSource
import sz.szsmk.citizencard.retrofitrxjava.newversion.NewHttpApi
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource
import sz.szsmk.citizencard.ui.newversion.fragment.view.BusCodeMvpView
import sz.szsmk.citizencard.util.*
import sz.szsmk.citizencard.widget.GlobalVariables
import java.util.*
import javax.inject.Inject

/**
 *  author : hyt
 *  date : 2020/10/13
 *  description :
 */
class BusCodePresenter@Inject constructor(var httpDateSourceNotUse: NetworkDateSource)
    : AppBasePresenter<BusCodeMvpView>(){

    //请求openid
    fun getOpenId(access_token: String){
        val getOpenIdReq = GetOpenIdReq()
        getOpenIdReq.user_type = 0
        getOpenIdReq.access_token = access_token
        addSubscription(HttpDateSource.createApi()?.getOpenId(getOpenIdReq), object : ApiCallback<GetOpenIdRes?> {
            override fun onSuccess(response: GetOpenIdRes?) {
                response?.let {
                    ACache.get(DaggerApplication.getIns()).put("openId",response.openId)
                    checkIsOpenElecCard(it)
                }
            }

            override fun onFailure(model: BaseBean?, e: Throwable?) {
                model?.let { mvpView.onFail(it) }
            }
        })
    }

    //查询是否实名  这里的实名 和 外面的L2实名  不是一个概念
    fun checkIsOpenElecCard(getOpenIdRes: GetOpenIdRes){
        val request = CommonRequest()
        request.openId = getOpenIdRes.openId
        ObjectSignatureUtil.signaturePreAuthRequest(request)
        addSubscription(HttpDateSource.createApi(NewHttpApi::class.java, Constant.DZ_BASE_URL)?.checkIsRealName(request),
                object : ApiCallback<CheckIsRealName2Res?> {
                    override fun onSuccess(response: CheckIsRealName2Res?) {
                        response?.let {
                            //实名判断
                            val isRealName: String = response.data.isRealName
                            //0 未实名 1实名
                            if (isRealName == "0") {
                                //签协议
                                mvpView.realNameFalse()
                            } else if (isRealName == "1") {
                                ACache.get(activity).put("bus_register","1")
                                //如果实名  获取 和那个银行签的协议   建设银行 000003
                                queryDzsmkAgreement(getOpenIdRes)
                            }
                        }
                    }

                    override fun onFailure(model: BaseBean?, e: Throwable?) {
                        model?.let { mvpView.onFail(it) }
                    }
                })
    }

    //相当于登录
    fun preAuthThird(getOpenIdRes: GetOpenIdRes, channelId: String){
        val preAuthThiedReq = PreAuthThiedReq()
        preAuthThiedReq.mobileNumber = getOpenIdRes.mobile + ""
        preAuthThiedReq.openId = getOpenIdRes.openId
        preAuthThiedReq.userId = getOpenIdRes.userId.toString()
        preAuthThiedReq.photoUrl = ""
        preAuthThiedReq.channelId = channelId
        ObjectSignatureUtil.signaturePreAuthRequest(preAuthThiedReq)
        addSubscription(HttpDateSource.createApi(NewHttpApi::class.java, Constant.DZ_BASE_URL)?.preAuthThird(preAuthThiedReq),
                object : ApiCallback<PreAuthThirdRes?> {
                    override fun onSuccess(response: PreAuthThirdRes?) {
                        response?.let {
                            val code: String = response.code
                            if (code == "0000") {
                                val data: PreAuthThirdRes.DataBean = response.getData()
                                val json = Gson().toJson(data)
                                ACache.get(DaggerApplication.getIns()).put("token", response.getData().getToken())
                                val preAuthResult = Gson().fromJson(json, PreAuthResult::class.java)
                                GlobalVariables.getInstance(DZSmkAppInit.getInstance().context)
                                        .setPreAuthResult(DaggerApplication.getIns(), preAuthResult)
                                getQrNumber()
                            } else {

                            }
                        }
                    }

                    override fun onFailure(model: BaseBean?, e: Throwable?) {
                        model?.let { mvpView.onFail(it) }
                    }
                })
    }

    //查协议 获取 channelId
    fun queryDzsmkAgreement(getOpenIdRes: GetOpenIdRes){
        val queryDzsmkAgreementReq = QueryDzsmkAgreementReq()
        queryDzsmkAgreementReq.openId = getOpenIdRes.openId
        queryDzsmkAgreementReq.userType = 0
        addSubscription(HttpDateSource.createApi()?.queryDzsmkAgreement(queryDzsmkAgreementReq),
                object : ApiCallback<QueryDzsmkAgreeMentRes?> {
                    override fun onSuccess(response: QueryDzsmkAgreeMentRes?) {
                        response?.let {
                            //这里用缓存是因为 后面签名方法里  是使用缓存的 channelId
                            ACache.get(DaggerApplication.getIns()).put("channelId", response.channelId)
                            preAuthThird(getOpenIdRes, response.channelId)
                        }
                    }

                    override fun onFailure(model: BaseBean?, e: Throwable?) {
                        model?.let { mvpView.onFail(it) }
                    }
                })
    }

    private var qrImgRefreshTime = 60
    private var qrAvaliTime = 60 //二维码有效时间S

    //获取二维码
    fun getQrNumber() {
        var qcr: QrCodeNumberResult? = null
        val daoSession = DaggerApplication.getmDaoSession()
        val sysConfDao = daoSession.sysConfDao
        val myQrCodeNumberDao = daoSession.myQrCodeNumberDao

        var offlineCount = 0 //离线生产个数

        val sysConfs = sysConfDao.loadAll()
        if (null != sysConfs && sysConfs.size > 0) {
            val sysConf = sysConfs[0]
            offlineCount = sysConf.offlineCount
            qrAvaliTime = sysConf.qrAvaliTime
            qrImgRefreshTime = sysConf.qrImgRefreshTime
        }
        val hasNetwork = CommonUtils.hasNetwork(DaggerApplication.getIns())

        val myQrCodeNumbers = myQrCodeNumberDao.loadAll()
        for (myQrCodeNumber in myQrCodeNumbers) {
            //有1秒的冗余，若快1秒就到期了，也认为是过期了
            if (System.currentTimeMillis() > myQrCodeNumber.expireTime - 1000) {
                myQrCodeNumberDao.delete(myQrCodeNumber)
            }
        }
        //loadAll不会返回个null
        val myQrCodeNumbersUsables = myQrCodeNumberDao.loadAll()
        val hasQrCodeCount = myQrCodeNumbersUsables.size //还有多少个有效的二维码


        if (!hasNetwork) { //没有网络
            if (hasQrCodeCount > 0) {
                val myQrCodeNumber = myQrCodeNumbersUsables[0]
                qcr = QrCodeNumberResult()
                qcr.resultCode = Constant.QUERY_QR_RESULT_AUTHED
                qcr.qrCode = myQrCodeNumber.qrNumber
                mvpView.onGainQrCodeNumber(qcr)
                mvpView.needRefreshCode(true)
            } else { //若没有二维码，可能是未实名或实名完了所有的码都过期了，反正就是要提示用户要去连网
                mvpView.onNoQrCodeUsed()
            }

            mvpView.handlerRefreshAndVibrator()
        } else {
            //需要向网络请求多少个二维码
            val needQrCode = offlineCount - hasQrCodeCount + 1
            val qrr = QrCodeNumberRequest()
            qrr.count = needQrCode.toString() + ""
            val longitude = SecureSharedPreferences.getString(Constant.LONGITUDE)
            val latitude = SecureSharedPreferences.getString(Constant.LATITUDE)
            qrr.lnt = longitude
            qrr.lat = latitude
            ObjectSignatureUtil.signatureRequest(qrr)
            val json = Gson().toJson(qrr)

            addSubscription(HttpDateSource.createApi(NewHttpApi::class.java, Constant.DZ_BASE_URL)?.getQrNumber(qrr), object : ApiCallback<QrNumberResponse?> {
                override fun onSuccess(qrNumberResponse: QrNumberResponse?) {
                    qrNumberResponse?.let {
                        val code = qrNumberResponse.code
                        if (code == "0000") {
                            val data = qrNumberResponse.data
                            val json = Gson().toJson(data)
                            val qrr = Gson().fromJson(json, QrCodeNumberResult::class.java)
                            if (data == null) {
                                return@let
                            }
                            if (Constant.QUERY_QR_RESULT_AUTHED == qrr.resultCode) {
                                val qrList = qrr.qrList as ArrayList<QrCodeNumber>
                                val qrString: MutableList<String?> = ArrayList()
                                for (qrCodeNumber in qrList) {
                                    qrString!!.add(qrCodeNumber.qrString)
                                }
                                if (null != qrString && qrString.size > 1) { //若是大于一个，则多余的则存在数据库
                                    for (i in 1 until qrString.size) {
                                        val qrCode = qrString[i]
                                        val expireTime: Long = System.currentTimeMillis() + qrAvaliTime * 1000
                                        val myQrCodeNumber = MyQrCodeNumber()
                                        myQrCodeNumber.expireTime = expireTime
                                        myQrCodeNumber.qrNumber = qrCode
                                        myQrCodeNumberDao.insert(myQrCodeNumber)
                                    }
                                }
                                Collections.shuffle(qrString) //测试，随便一个数出来看看
                                if (null != qrString && qrString.size > 0) {
                                    qrr.qrCode = qrString[0] //展示的码
                                    mvpView.needRefreshCode(true) //是需要刷新code的
                                }
                                mvpView.handlerRefreshAndVibrator()
                            }
                            if (mvpView != null) {
                                mvpView.onGainQrCodeNumber(qrr)
                            }
                        }
                    }
                }

                override fun onFailure(model: BaseBean?, e: Throwable?) {
                    model?.let { mvpView.onFail(it) }
                }
            })

        }
    }

}